<template>
  <div class="L-orgRef">
    <div class="L-top-bar">
      <form action="/">
        <van-search v-model="refData.keyword" show-action placeholder="请输入搜索关键词" @search="onSearch">
          <template #action>
            <span @click="onSearch">搜索</span>
            <span @click="handleRefCancle()" style="margin-left:10px">取消</span>
          </template>
        </van-search>
      </form>
    </div>

    <div class="L-orgTree">
      <van-checkbox-group v-model="refData.selecteddata" ref="checkboxGroup">
        <RefOrgTree :listMode="refData.listMode" :selecteddata="refData.selecteddata" :mode="refData.mode"
          :bo="refData.bo" :orgData="refData.orgData" :handleExpand="handleExpand" :handleChecked="handleChecked">
        </RefOrgTree>
      </van-checkbox-group>
    </div>



  </div>
  <van-tabbar safe-area-inset-bottom v-if="refData.mode === 'multi'">
    <div class="L-orgRef-tabbar">
      <van-button color="#1989fb" type="primary" style="width:90%" @click="handleConfirm">确定</van-button>
    </div>
  </van-tabbar>
</template>

<script lang="ts" setup>
import RefOrgTree from "./RefOrgTree.vue";
import { ref, reactive, watch, onMounted, inject } from "vue";
import { useFieldMap } from "@/hooks/hooks.js";
const { getMapInfo } = useFieldMap();

import { showToast, showLoadingToast, closeToast } from "vant";
import { useRoute, useRouter } from "vue-router";
import { apiConfigurable, apiRefListNew } from "@/request/api/api";
import { useRefStore } from "@/stores/ref";
const refStore = useRefStore();

const route = useRoute();
const router = useRouter();
const refData = reactive({
  bo: "employee",
  orgData: [],
  mode: "normal",
  keyword: "",
  // sval: route.query.conditionVal,
  sval: "",
  list: [],
  loading: false,
  page: 0,
  rebackobject: { reBackflag: false },
  // fieldref: route.query.fieldref,
  fieldref: "",
  selecteddata: [],
  listMode: "tree",
});

const props = defineProps({
  refParams: {
    type: Object,
    default: {},
  },
  handleRefClick: {
    type: Function,
    default: () => { },
  },
  handleRefCancle: {
    type: Function,
    default: () => { },
  },
  refMode: {
    type: String,
    default: "normal",
  },
  refObject: {
    type: String,
    default: "",
  },
});

refData.mode = props.refMode;
refData.bo = props.refObject;


onMounted(() => {
  onLoad();
});

function handleExpand(item, isShow) {
  // item.extra.show = isShow;

  if (!isShow) {
    item.extra.show = isShow
    return
  }

  const loadParams = props.refParams;
  let data = {
    ref_object: loadParams.object,
    ref_toobject: loadParams.toobject,
    ref_tofieldas: loadParams.field,
    ref_inview: loadParams.inview || "",
    // ref_inview: "",
    view_page: refData.page,
    view_id: loadParams.id,
    ref_classname: "",
    ref_params: "",

    ref_conditionval: refData.keyword,
    ref_depid: item.id, // 部门id，默认所有
    conf_searchall: false
  };

  data.ref_inview = data.ref_inview.replace(':in:', ':in:' + this.sval)
  //console.log('data.ref_inview', data.ref_inview)
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  })

  apiConfigurable('ref.listnew.do', data).then(res => {
    //console.log(res)
    if (res.data.flag === '1') {
      showToast(res.data.des)
      if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
        this.loginout()
      } else {
        this.$router.go(-1)
      }
    } else {
      item.extra.show = isShow

      // this.$set(item, "children", res.data.jsondata.outdata)
      item.children = res.data.jsondata.outdata
    }
  }).finally(() => {
    closeToast()
  })
}


interface returnObjInterface {
  id: string,
  title: string,
  [key: string]: string

}
async function handleChecked(item, isChecked) {
  if (refData.mode === "normal") {
    const returnObj:returnObjInterface = {
      title: item.extra.sname,
      id: item.id,
    };
    item.extra.checked = isChecked;
    const refParams = props.refParams;

    //字段映射
    const data = {
      ref_object: refParams.object,
      ref_id: item.id,
      ref_toobject: refParams.toobject,
      ref_tofieldas: refParams.field,
      ref_tofield: refParams.field,
      ref_classname: refParams.classname,
      ref_params: refParams.params,
    };

    const mapRes = await getMapInfo(data);

    const outdata = mapRes.data.jsondata.outdata;

    if (Object.getOwnPropertyNames(outdata).length > 2) {
      returnObj.fieldmap = outdata;
      returnObj.mapobject = refParams.toobject;
    }


    props.handleRefClick(returnObj);
  }
}

function handleConfirm() {
  let id = "";
  let title = "";

  for (let i = 0; i < refData.selecteddata.length; i++) {
    const item = refData.selecteddata[i];
    id += `${item.id};`;
    title += `${item?.extra.sname};`;
  }
  const returnObj = {
    title,
    id,
  };

  props.handleRefClick(returnObj);
}

function onLoad() {
  const loadParams = props.refParams;
  console.log(loadParams,2323)
  let data = {
    ref_object: loadParams.object,
    ref_toobject: loadParams.toobject,
    ref_tofieldas: loadParams.field,
    ref_inview: loadParams.inview || "",
    // ref_inview: "",
    view_page: refData.page,
    view_id: loadParams.id || loadParams.sRefKey || loadParams.viewId,
    ref_classname: loadParams.classname,
    ref_params: loadParams.params,
    ref_conditionval: refData.keyword,
    conf_searchall: false  //查询全部，默认false
  };

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });
  apiRefListNew(data).then((res) => {
    if (res?.code === 0) {
      refData.orgData = res.data.jsondata.outdata;
      closeToast();
    }
  });
}

function onSearch() {
  if (refData.keyword === "") {
    refData.listMode = "tree";
  } else {
    refData.listMode = "list";
  }
  onLoad();
}
</script>

<style scoped>
.L-orgRef {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: scroll;

}

.L-orgTree {
  padding: 5px 8px;
  box-sizing: border-box;
  margin-bottom: 40px;
  flex-grow: 1;
  flex-shrink: 1;
  overflow: scroll;
  /* margin-top: 50px; */
}

.L-top-bar {
  /* position: fixed; */
  width: 100%;
  height: 55px;
  border-bottom: 1px solid #f0f0f0;
  flex-grow: 0;
  flex-shrink: 0;


  /* top: 0;
  left: 0; */
}
</style>
